package yagwl.client.widget;

import yagwl.client.widget.internal.YClientBundle;
import yagwl.client.widget.internal.YCssResource;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;

public class FocusItem extends Composite {
  private static final YCssResource ycss = YClientBundle.I.css();
  private final FocusPanel rootFocusPanel = new FocusPanel();
  private final FlowPanel flowPanel = new FlowPanel();
  private CheckBox checkBox;
  private Object object;
  private int iconCount = 0;

  public FocusItem() {
    SimplePanel simplePanel = new SimplePanel();
    simplePanel.setStyleName(ycss.zPositionRelative());
    simplePanel.add(flowPanel);
    rootFocusPanel.setWidget(simplePanel);
    initWidget(rootFocusPanel);
  }
  
  public void enableSelection() {
    checkBox = new CheckBox();
    flowPanel.add(checkBox);
    checkBox.setStyleName(ycss.zFloatLeft());
  }
  
  public boolean isSelected() {
    return checkBox.getValue();
  }
  
  public void setObject(Object object) {
    this.object = object;
  }
  
  public Object getObject() {
    return object;
  }

  public void setContent(Widget w) {
    flowPanel.add(w);
  }

  public void addIcon(final Image icon, String label, final ClickCallback callback) {
    ++iconCount;
    if (iconCount == 1)
      icon.setStyleName(ycss.focusItemIcon1());
    else
      icon.setStyleName(ycss.focusItemIcon2());
    icon.setTitle(label);
    icon.setVisible(false);
    flowPanel.add(icon);
    icon.addClickHandler(new ClickHandler() {
      @Override
      public void onClick(ClickEvent event) {
        callback.onClick(object);
      }
    });
    rootFocusPanel.addMouseOverHandler(new MouseOverHandler() {
      @Override
      public void onMouseOver(MouseOverEvent event) {
        icon.setVisible(true);
      }
    });
    rootFocusPanel.addMouseOutHandler(new MouseOutHandler() {
      @Override
      public void onMouseOut(MouseOutEvent event) {
        icon.setVisible(false);
      }
    });
  }

  public interface ClickCallback {
    void onClick(Object object);
  }

  public enum Location {
    TopRight
  }
}
